# Aneke.py
# ----------------------------
# This module encapsulates the core functionalities
# like the editor widget and the lexer

from PyQt4 import QtGui, QtCore
import os.path as File

class NumberedBar( QtGui.QWidget ):
	"""
	The numbered sidebar
	"""
	def __init__( self, parent=None ):
		QtGui.QWidget.__init__( self )
		self.setFixedWidth( self.fontMetrics().width( "000" ) )
		
	def setCurrentLine( self, lineno ):
		self.currentLine = lineno
		
	def setEditor( self, editor):
		self.editor = editor
		self.connect(
			editor.document().documentLayout(),
			QtCore.SIGNAL( "update(const QRectF &)" ),
			QtCore.SLOT( "update()" )
		)
		self.connect(
			editor.verticalScrollBar(),
			QtCore.SIGNAL( "valueChanged(int)" ),
			QtCore.SLOT( "update()" )
		)
	# BOGUS
	#def paintEvent( self, event ):
		#layout 			= self.editor.document().documentLayout()
		#yPosition 	= self.editor.verticalScrollBar().value()
		#pageBottom 	= yPosition + self.editor.viewport().height()
		#lineCount 	= 1
		
		#painter = QtGui.QPainter( self )
		
		#self.currentRect = QtCore.QRect()
		
		#block = self.editor.document().begin()
		#while block.isValid() and block.length() > 1:
			#boundRect = layout.blockBoundingRect( block )
			#position  = boundRect.topLeft()
			#if (position.y() + boundRect.height()) < yPosition:
				#continue
			#if position.y() > pageBottom:
				#break
			
			#txt = str( lineCount )
			#painter.drawText(
				#self.width() - self.fontMetrics().width( txt ),
				#QtCore.qRound( position.y() ) - yPosition + self.fontMetrics().ascent(),
				#txt
			#)
			
			#block.next()
			#lineCount += 1

class Editor( QtGui.QFrame ):
	def __init__( self, filename="" ):
		QtGui.QFrame.__init__( self )
		
		self.setFrameStyle( QtGui.QFrame.StyledPanel or QtGui.QFrame.Sunken )
		self.setLineWidth( 2 )
		
		self.editor = TextEditor()
		self.editor.installEventFilter( self )
		
		if File.exists(filename):
			self.setFilename( filename )
		else:
			self.setFilename( "" )
		
		self.numbar = NumberedBar( self )
		self.numbar.setEditor( self.editor )
		#self.setCurrentLine( 5 ) # TESTE
		
		box = QtGui.QHBoxLayout( self )
		box.setSpacing( 0 )
		box.setMargin( 0 )
		box.addWidget( self.numbar )
		box.addWidget( self.editor )
		
	def setFilename( self, filename ):
		self.filename = filename
		
	def setCurrentLine( self, lineno ):
		self.currentLine = lineno
		self.numbar.setCurrentLine( lineno )
		
	def getPlainText( self ):
		return self.editor.toPlainText()
		
class TextEditor( QtGui.QTextEdit ):
	"""
	The editor widget is container for the text typed
	and controls the basic actions like copy, paste and undo
	"""
	def __init__( self ):
		QtGui.QTextEdit.__init__(self)
		font = QtGui.QFont()
		font.setFamily("Andale Mono")
		font.setFixedPitch(True)
		font.setPointSize(11)
		self.setFont(font)
		
		self.setLineWrapMode( QtGui.QTextEdit.NoWrap )
		self.setFrameStyle( QtGui.QFrame.NoFrame )